//
//  LoginViewController.m
//  iWeddingDirectory
//
//  Created by Tung Ngo on 6/4/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ForgotPasswordViewController.h"
#import <CoreText/CoreText.h>
#import <QuartzCore/QuartzCore.h>
#import "API.h"
#import "User.h"
#import "UserViewController.h"
#import "InboxViewController.h"
#import "Mail.h"

@implementation LoginViewController
@synthesize buttonLogin;
@synthesize textFieldUsername;
@synthesize textFieldPassword;
@synthesize waitingIndicator;
@synthesize buttonRegister;
@synthesize buttonForgotPassword;
@synthesize buttonInbox;
@synthesize buttonMyDetail;
@synthesize lblPassword,lblUsername;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Login" image:[UIImage imageNamed:@"login.png"] tag:0];
        self.tabBarItem = item;
        [item release];
        
        self.title = @"Login";
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [buttonRegister release];
    [buttonForgotPassword release];
    [textFieldUsername release];
    [textFieldPassword release];
    [buttonLogin release];
    [waitingIndicator release];
    [super dealloc];
}

#pragma mark - View lifecycle

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
  
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Login";
    waitingIndicator.hidden = YES;
    
    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    if (username != nil) {
        textFieldUsername.text = username;
        NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
        textFieldPassword.text = password;
        buttonRegister.hidden = YES;
        buttonForgotPassword.hidden = YES;
        [buttonLogin setTitle:@"Logout" forState:UIControlStateNormal];
        buttonMyDetail.hidden = NO;
        buttonInbox.hidden = NO;
        lblPassword.hidden = YES;
        lblUsername.hidden = YES;
        textFieldUsername.hidden = YES;
        textFieldPassword.hidden = YES;
    }
    else {
        buttonMyDetail.hidden = YES;
        buttonInbox.hidden = YES;
    }
        
    
    NSMutableAttributedString *registerString = [[NSMutableAttributedString alloc] initWithString:@"register"];
    [registerString addAttribute:(NSString *)kCTUnderlineStyleAttributeName value:[NSNumber numberWithInt:kCTUnderlineStyleThick] range:NSMakeRange(0, [registerString length])];
    CATextLayer *registerTextLayer = [[CATextLayer alloc] init];
    registerTextLayer.frame = buttonRegister.titleLabel.bounds;
    registerTextLayer.string = registerString;
    [buttonRegister.titleLabel.layer addSublayer:registerTextLayer];
    [registerString release];
    [registerTextLayer release];
    
    NSMutableAttributedString *forgotPasswordString = [[NSMutableAttributedString alloc] initWithString:@"forgot password"];
    //[forgotPasswordString setFont:[UIFont systemFontSize:14]];

    [forgotPasswordString addAttribute:(NSString *)kCTUnderlineStyleAttributeName value:[NSNumber numberWithInt:kCTUnderlineStyleThick] range:NSMakeRange(0, [forgotPasswordString length])];
    CATextLayer *forgotPasswordTextLayer = [[CATextLayer alloc] init];
    forgotPasswordTextLayer.frame = buttonForgotPassword.titleLabel.bounds;
    forgotPasswordTextLayer.string = forgotPasswordString;
    [buttonForgotPassword.titleLabel.layer addSublayer:forgotPasswordTextLayer];
    [forgotPasswordString release];
    [forgotPasswordTextLayer release];
        
    
}

- (void)viewDidUnload
{
    [self setButtonRegister:nil];
    [self setButtonForgotPassword:nil];
    [self setTextFieldUsername:nil];
    [self setTextFieldPassword:nil];
    [self setButtonLogin:nil];
    [self setWaitingIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Text field delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Notificantion handlers

- (void)onLogin:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kLoginNotification object:nil];
    [waitingIndicator stopAnimating];
    [self.view setUserInteractionEnabled:YES];
    
    NSDictionary *result = [notification userInfo];
    NSLog(@"result = %@", result);
    NSString *status = [result objectForKey:@"status"];
    if ([status isEqualToString:@"error"]) {
        NSString *message = [result objectForKey:@"error"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    else if ([status isEqualToString:@"ok"]) {
      
        
        //buttonLogin.frame = CGRectMake(buttonLogin.frame.origin.x, buttonLogin.frame.origin.y-150, buttonLogin.frame.size.width, buttonLogin.frame.size.height);
        
        [[NSUserDefaults standardUserDefaults] setValue:[result objectForKey:@"cookie"] forKey:@"userCookie"];
        [[NSUserDefaults standardUserDefaults] setObject:textFieldUsername.text forKey:@"username"];
        [[NSUserDefaults standardUserDefaults] setObject:textFieldPassword.text forKey:@"password"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        NSDictionary *user = [result objectForKey:@"user"];
        NSString *username = [user objectForKey:@"username"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iWeddingDirectory" message:[NSString stringWithFormat:@"Hello %@, welcome back to the iWedding Directory.", username] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [[NSUserDefaults standardUserDefaults] setObject:user forKey:@"logged_in_user"];

        [alert setTag:100];
//        alert.delegate = self;
        [alert show];
        [alert release];
    }
}

- (void)onGetDetail:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kMyDetailNotification object:nil];
    [waitingIndicator stopAnimating];
    [self.view setUserInteractionEnabled:YES];
    
    NSDictionary *result = [notification userInfo];
    NSLog(@"result = %@", result);
    NSString *status = [result objectForKey:@"status"];
    if ([status isEqualToString:@"error"]) {
        NSString *message = [result objectForKey:@"error"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    else if ([status isEqualToString:@"ok"]) {
        
        User *user = [[User alloc] init];
        NSDictionary *userinfo = [[result objectForKey:@"user"] objectForKey:@"user_info"];
        user.name = [[userinfo objectForKey:@"firstname"] stringByAppendingFormat:@"%@", [userinfo objectForKey:@"lastname"]];
        user.username = [userinfo objectForKey:@"username"];
        user.email = [userinfo objectForKey:@"email"];
        user.url = [userinfo objectForKey:@"url"];
        user.zip = [userinfo objectForKey:@"zip"];
        user.state = [userinfo objectForKey:@"state"];
        user.country = [userinfo objectForKey:@"country"];
        user.phone = [userinfo objectForKey:@"phone"];
        user.registered = [userinfo objectForKey:@"registered"];
        user.address = [userinfo objectForKey:@"address"];
        user.city = [userinfo objectForKey:@"city"];
        
        NSLog(@"username = %@",user.username);
        
        UserViewController *uvc = [[UserViewController alloc] initWithNibName:@"UserViewController" bundle:nil];
        [uvc setUser:user];
        [self.navigationController pushViewController:uvc animated:YES];
        [uvc release];
        //[user release];               
    }
}

- (void)onGetInbox:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kInboxNotification object:nil];
    [waitingIndicator stopAnimating];
    [self.view setUserInteractionEnabled:YES];
    
    NSDictionary *result = [notification userInfo];
    NSLog(@"result = %@", result);
    NSString *status = [result objectForKey:@"status"];
    if ([status isEqualToString:@"error"]) {
        NSString *message = [result objectForKey:@"error"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    else if ([status isEqualToString:@"ok"]) {
        InboxViewController *uvc = [[InboxViewController alloc] initWithNibName:@"InboxViewController" bundle:nil];
        NSMutableArray *messages = [[NSMutableArray alloc] initWithCapacity:0];
        NSArray *_categories = [[result objectForKey:@"user"] objectForKey:@"messages"];
        for (NSDictionary *_category in _categories) {
            Mail *message = [[Mail alloc] init];
            //int categoryId = [[_category objectForKey:@"id"] intValue];
            //NSString *title = @"This is the message title";//[_category objectForKey:@"title"];
            NSString *datecreated = [_category objectForKey:@"date"];
            NSString *content = [_category objectForKey:@"message"];
            NSString *author = [_category objectForKey:@"author"];

            //category.categoryId = categoryId;
            message.title = [NSString stringWithFormat:@"From %@", author];
            message.datecreated = datecreated;
            message.from = author;
            message.content = content;
            [messages addObject:message];
            [message release];
        }
        [uvc setMailbox:messages];
        [self.navigationController pushViewController:uvc animated:YES];
        [uvc release];
        //[user release];               
        
    }
}

#pragma mark - AlertView delegate
//-(void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex  // after animation

{
    if( [alertView tag] == 100 ){
        buttonMyDetail.hidden = NO;
        buttonInbox.hidden = NO;
        
        //Return to Inquiry screen if needed:
        if( [[NSUserDefaults standardUserDefaults] valueForKey:@"push_back"] == @"yes" ){
            [self.navigationController popViewControllerAnimated:YES];
        }
    
        [buttonLogin setTitle:@"Logout" forState:UIControlStateNormal];
        buttonRegister.hidden = YES;
        buttonForgotPassword.hidden = YES;
        buttonMyDetail.hidden = NO;
        buttonInbox.hidden = NO;
        
        textFieldPassword.hidden = YES;
        textFieldUsername.hidden = YES;
        lblUsername.hidden = YES;
        lblPassword.hidden = YES;
        
        //[NSUserDefaults standardUserDefaults] setObject: forKey:<#(NSString *)#>
    }

}

-(IBAction)onButtonInboxClicked:(id)sender
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onGetInbox:) name:kInboxNotification object:nil];
    NSString *userCookie = [[NSUserDefaults standardUserDefaults] valueForKey:@"userCookie"];
    API *api = [API sharedInstance];
    [api getUserInbox:userCookie];    
    waitingIndicator.hidden = NO;
}

-(IBAction) onButtonMyDetailClicked:(id)sender
{
    NSString *userCookie = [[NSUserDefaults standardUserDefaults] valueForKey:@"userCookie"];
    NSLog(@"userCookie = %@", userCookie);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onGetDetail:) name:kMyDetailNotification object:nil];
    API *api = [API sharedInstance];
    [api getUserDetail:userCookie];
    waitingIndicator.hidden = NO;

}

#pragma mark - Button click handlers

- (IBAction)onButtonRegisterClicked:(id)sender {
    RegisterViewController *vcRegister = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:vcRegister animated:YES];
    [vcRegister release];
}

- (IBAction)onButtonForgotPasswordClicked:(id)sender {
    ForgotPasswordViewController *vcForgotPassword = [[ForgotPasswordViewController alloc] init];
    [self.navigationController pushViewController:vcForgotPassword animated:YES];
    [vcForgotPassword release];
}

- (IBAction)buttonLoginClicked:(id)sender {
    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    if (username != nil) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"username"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"password"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [buttonLogin setTitle:@"Login" forState:UIControlStateNormal];
        textFieldUsername.text = @"";
        textFieldPassword.text = @"";
        
        lblUsername.hidden = NO;
        lblPassword.hidden = NO;
        buttonForgotPassword.hidden = NO;
        buttonRegister.hidden = NO;
        textFieldPassword.hidden = NO;
        textFieldUsername.hidden = NO;
        
        buttonRegister.hidden = NO;
        buttonForgotPassword.hidden = NO;
        buttonMyDetail.hidden = YES;
        buttonInbox.hidden = YES;
        
    }
    else {
        if (textFieldUsername.text == nil || [textFieldUsername.text length] == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"You must fill the username first" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        if (textFieldPassword.text == nil || [textFieldPassword.text length] == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"You must fill the password first" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        
        [textFieldUsername resignFirstResponder];
        [textFieldPassword resignFirstResponder];
        
        [waitingIndicator setHidesWhenStopped:YES];
        [waitingIndicator setHidden:NO];
        [waitingIndicator startAnimating];
        [self.view setUserInteractionEnabled:NO];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLogin:) name:kLoginNotification object:nil];
        API *api = [API sharedInstance];
        [api loginWithUsername:textFieldUsername.text andPassword:textFieldPassword.text];
        waitingIndicator.hidden = NO;
    }
}

@end
